# 商品信息文件
import hashlib
import os
import random
import time
from datetime import datetime

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from pet_admin.models import Orders_Main, Users, Goods


def find(request, pageIndex=1):
    """
        查询全部订单信息视图
    """
    orders = Orders_Main.objects  # 实例化Orders对象
    orders = orders.filter(order_status__lt=9).order_by('order_id')  # 过滤出来状态小于9的有效订单

    searchKey = []
    # 获取并判断搜索条件
    user_name = request.GET.get("user_name", None)  # 获取表单提交数据
    if user_name:
        user_name = user_name.replace(" ", "")
        orders = orders.filter(user_id__user_name__contains=user_name)
        searchKey.append("user_name=" + user_name)

    # type_id = request.GET.get("type_id", None)  # 获取表单提交数据
    # if type_id:
    #     goods = goods.filter(type_id__contains=type_id)
    #     searchKey.append("type_id=" + type_id)

    # 分页处理
    pageIndex = int(pageIndex)
    page = Paginator(orders, 10)  # 每页多少条
    maxPage = page.num_pages  # 获取最大页数
    # 处理页码越界
    if pageIndex > maxPage:
        pageIndex = maxPage
    if pageIndex < 1:
        pageIndex = 1
    orders = page.page(pageIndex)  # 获取当前页数据
    pages = page.page_range  # 获取页码列表信息

    # 遍历当前商品信息并封装对应的商品类型
    for order in orders:
        user = Users.objects.get(user_id=order.user_id)
        order.user_name = user.user_name

    context = {"orders": orders, "pages": pages, "pageIndex": pageIndex, "maxPage": maxPage,
               "searchKey": searchKey}
    return render(request, 'pet_admin/order_manage/index.html', context)


def add(request):
    """
        添加订单视图
    """
    goods = Goods.objects.values("good_id", "good_name", "good_price")
    context = {"goods": goods}
    return render(request, "pet_admin/order_manage/add.html", context)


def insert(request):
    """
        执行添加程序方法
    """
    try:
        goods = Orders_Main()
        goods.good_name = request.POST["good_name"]
        print(request.POST["type_id"])
        goods.type_id = request.POST["type_id"]
        # 处理商品图片
        good_pic_file = request.FILES.get('good_path', None)
        if not good_pic_file:
            return HttpResponse("没有上传图片")
        good_path = str(time.time()) + "." + good_pic_file.name.split('.').pop()
        destination = open("./static/uploads/goods_path/" + good_path, "wb+")
        for chunk in good_pic_file.chunks():
            destination.write(chunk)
        destination.close()
        goods.good_path = good_path  # 商品图片

        goods.good_price = request.POST["good_price"]  # 单价
        goods.good_hot = request.POST["good_hot"]  # 热销类型
        goods.good_createtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 商品创建时间
        goods.good_createuser = request.session["adminUser"]["user_id"]  # 取session中的用户ID
        goods.good_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 商品修改时间
        goods.good_updateuser = request.session["adminUser"]["user_id"]  # 取session中的用户ID
        goods.save()
        context = {"info": "添加成功"}

    except Exception as err:
        print(err)
        context = {"info": "添加失败"}

    return render(request, "pet_admin/info.html", context)


def deluser(request, good_id):
    """
       执行删除程序的方法
    """
    try:
        good = Orders_Main.objects.get(good_id=good_id)
        good.good_status = 9
        good.good_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        good.save()
        context = {"info": "删除成功"}

    except Exception as err:
        print(err)
        context = {"info": "删除失败"}

    return render(request, "pet_admin/info.html", context)
